package com.gict.antifraudback.controller.front.login;

import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gict.antifraudback.constants.RedisKeyConstants;
import com.gict.antifraudback.entity.User;
import com.gict.antifraudback.exception.BusinessException;
import com.gict.antifraudback.exception.MyException;
import com.gict.antifraudback.redis.RedisService;
import com.gict.antifraudback.result.ResultEnum;
import com.gict.antifraudback.result.ResultView;
import com.gict.antifraudback.service.UserService;
import com.gict.antifraudback.utils.DESCode;
import com.gict.antifraudback.utils.NoAuthorization;
import com.gict.antifraudback.utils.UserThreadLocal;
import com.gict.antifraudback.utils.Validator;
import com.gict.antifraudback.vo.LoginVo;
import com.gict.antifraudback.vo.MailUtil;
import com.gict.antifraudback.vo.RegisterVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ThinkPad
 */
@RestController
@Slf4j
@RequestMapping("/mapi")
public class FrontLoginController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisService redisService;

    @PostMapping("/login")
    @NoAuthorization
    public ResultView login(@RequestBody LoginVo loginVo){
        String password = DESCode.encode(loginVo.getPassword());
        String email = loginVo.getEmail();
        User user = userService.forntLogin(email, password);
        if (user != null) {

            // 获取token
            String accessToken = userService.crateFrontToken(user.getId());

            Map<String, String> map = new HashMap<>();
            map.put("accessToken", accessToken);
            return ResultView.ok(map);
        }

        return ResultView.error(ResultEnum.CODE_4);
    }

    @PostMapping("/logout")
    public ResultView logout(){
        String loginKey = String.format(RedisKeyConstants.FRONT_LOGIN_KEY, UserThreadLocal.get().getId());
        redisService.del(loginKey);
        return ResultView.ok();
    }

}
